package net.oschina.dajiangnan.wx.process.pay;

import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import net.oschina.dajiangnan.util.XStreamHelper;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import net.oschina.dajiangnan.wx.constants.Config;
import net.oschina.dajiangnan.wx.constants.Custom;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.PayNotifyReq;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.PayNotifyResp;


public class Pay_notify {

    private static Logger logger = Logger.getLogger(Pay_notify.class);
    
    public String process(HttpServletRequest req) throws Exception{
        
        req.setCharacterEncoding("utf-8");
        InputStream reqBody = req.getInputStream();
        String xmlStr = IOUtils.toString(reqBody);
        
        PayNotifyReq payNotifyReq = XStreamHelper.toBean(xmlStr, PayNotifyReq.class);
        logger.debug("微信支付系统向支付回调地址post内容如下:\r\n" + payNotifyReq);
        
        PayNotifyResp payNotifyResp = new PayNotifyResp();

        if(!payNotifyReq.islegalSign(Config.apikey)){
            
            payNotifyResp.setReturn_code("FAIL");
            payNotifyResp.setReturn_msg("payNotifyReq unlegalSign");
            logger.debug("payNotifyReq签名验证失败,支付回调地址给微信支付系统返回内容如下:\r\n" + payNotifyResp);
        }else{
        	Custom.wx.payListener(payNotifyReq.getOpenid(), payNotifyReq.getTransaction_id(), payNotifyReq.getOut_trade_no());

            payNotifyResp.setReturn_code("SUCCESS");
            payNotifyResp.setReturn_msg("OK");
            logger.debug("支付回调地址给微信支付系统返回内容如下:\r\n" + payNotifyResp);
        }
        return payNotifyResp.toString();
    }
}
